<template>
  <div class="container">
    <div class="treeandlegend-content" v-show="closetree">
      <div class="tree-content">
        <el-input
                class="filter-condition"
                placeholder="输入关键字进行过滤"
                v-model="filterText">
        </el-input>
        <el-tree
                class="filter-tree"
                :data="data"
                show-checkbox
                :props="defaultProps"
                @check="setlayer"
                default-expand-all
                :filter-node-method="filterNode"
                ref="tree">
        </el-tree>
      </div>
      <el-popover
              popper-class="wrap"
              class="legend-content"
              placement="right-end"
              width="200"
              trigger="click">
          <div class="legend-info">
              <div class="legend-info-title">
                  <span>图例</span>
              </div>
              <div class="legend-info-style" v-for="(val,key) in legendinfo" :key="key" @click="selectstyleshow(key)">
                  <div class="legend-info-style-block" :style="setlegendstyle(val)"></div>
                  <div class="legend-info-style-desc">
                      <span>{{key}}</span>
                  </div>

              </div>
          </div>
<!--        <img :src="legendurl" alt="未发现图例" class="legend-pic" >-->
              <div slot="reference" >
                <p class="legend-desc">图</p>
                <p class="legend-desc">例</p>
                <p class="legend-desc">></p>
              </div>
      </el-popover>
    </div>
    <landarrtibute  v-show='showoneattribute' :onelandarrtibutes="onelandarrtibutes"></landarrtibute>
    <timeline v-show="focusprojshow"></timeline>
    <manylayerattribute :landarrtibutes="propertiesarry" v-show="showattribute"></manylayerattribute>
    <analysisform :retgeoinfo="retgeoinfo" v-show="showanaret" @closewind='closesonwind'></analysisform>
      <toolsformap @selectmapimg="selectMapOrImg"></toolsformap>
      <measuretools :mapsformeasure="maps" @measureclick="measureclick"></measuretools>
    <div id="oneMap" class="map-container">
    </div>
    <div class="drawrow-content" v-show="showdraw">
      <el-row>
        <el-button icon="el-icon-search" circle @click="openselectdialog" title="依据产业类别选址"></el-button>
        <el-button type="primary" icon="el-icon-edit" circle @click="drawinfo" title="绘制分析范围"></el-button>
        <el-button type="success" icon="el-icon-check" circle  @click="commitgeoinfo" title="提交分析"></el-button>
        <el-button type="info" icon="el-icon-delete" circle title="清除数据" @click="delgeoinfo('open')"></el-button>
        <el-button type="danger" icon="el-icon-close" circle @click="delgeoinfo('close')" title="关闭"></el-button>
      </el-row>
    </div>
    <div>
      <div class="selectaddress-content" v-show="dialogFormVisible">
      <el-form :model="form" style="margin-top: 5px">
<!--        <el-form-item label="产业类别" :label-width="formLabelWidth">-->
<!--          <el-input v-model="form.name" autocomplete="off"></el-input>-->
<!--        </el-form-item>-->
        <el-form-item label="产业类别" :label-width="formLabelWidth">
          <el-select v-model="form.region" placeholder="请选择产业类别" >
              <el-option :label="item" :value="item" v-for="(item,index) in form.date1 ":key="index" ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" >
        <el-button @click="closeselectdialog" >取 消</el-button>
        <el-button type="primary" @click="selchange(form.region)" >选 址</el-button>
      </div>
    </div>
    </div>
  </div>
</template>

<script>
    import measuretools from "./components/measuretools";
    import toolsformap from "./components/toolsformap"
  import timeline from './components/timeline';
  import landarrtibute from "./components/landarrtibute";
  import manylayerattribute from "./components/manylayerattribute";
  import analysisform from "./components/analysisform";
  import Map from 'ol/Map.js';
  import View from 'ol/View.js';
  import {FullScreen,ScaleLine, defaults as defaultControls} from 'ol/control';
  import {Group as LayerGroup} from 'ol/layer';
  import Draw from 'ol/interaction/Draw';
  import Feature from 'ol/Feature';
  import VectorSource from 'ol/source/Vector';
  import {Vector as VectorLayer} from 'ol/layer';
  import {Icon, Style,Text,Circle as CircleStyle} from 'ol/style';
  import GeoJSON from 'ol/format/GeoJSON';
  import {WFS} from 'ol/format';
  import {Fill, Stroke} from 'ol/style';
  import Projection from "ol/proj/Projection";
  import {defaults} from 'ol/control.js';
  import {getWidth, getTopLeft} from 'ol/extent.js';
  import TileLayer from 'ol/layer/Tile.js';
  import TileWMS from 'ol/source/TileWMS';
  import WMTS from 'ol/source/WMTS.js';
  import WMTSTileGrid from 'ol/tilegrid/WMTS.js';
  import MousePosition from 'ol/control/MousePosition';
  import {createStringXY} from 'ol/coordinate';
  import PluggableMap from 'ol/PluggableMap';
  import {getVectorContext} from 'ol/render';
  import {sortFeature} from "../../utils/map/countFeaturestype";
  import {getLayerStyle} from "../../api/cydtRequest";
  import XYZ from "ol/source/XYZ"
  import {get as getProjection} from 'ol/proj';
  import MultiPolygon from 'ol/geom/MultiPolygon'
  import ImageWMS from 'ol/source/ImageWMS';
  import {Image as ImageLayer} from 'ol/layer';
  import {
    and as andFilter,
    equalTo as equalToFilter,
    like as likeFilter,
    intersects as intersectsFilter,
    or as orFilter
  } from 'ol/format/filter';
  import axios from "axios";
  import { register } from 'ol/proj/proj4';
  import proj4 from 'proj4';
  proj4.defs("EPSG:4490", "+proj=longlat +ellps=GRS80 +no_defs");
  register(proj4);
  PluggableMap.prototype.getEventPixel = function (event) {
    const viewportPosition = this.viewport_.getBoundingClientRect();
    let size = [viewportPosition.width, viewportPosition.height];
    const view = this.getView();
    if (view) {
      size = view.getViewportSize_();
    }
    const eventPosition =
            //FIXME Are we really calling this with a TouchEvent anywhere?
            'changedTouches' in event
                    ? /** @type {TouchEvent} */ (event).changedTouches[0]
                    : /** @type {MouseEvent} */ (event);
    return [
      ((eventPosition.clientX - viewportPosition.left) * size[0]) /
      viewportPosition.width,
      ((eventPosition.clientY - viewportPosition.top) * size[1]) /
      viewportPosition.height
    ];
  };
  export default {
    name: "oneMap",
    components: {
      timeline,
      landarrtibute,
      manylayerattribute,
      analysisform,
        toolsformap,
        measuretools
    },
    props:['changepage'],
    data(){
      return{
          legendinfo:{

          },
          legendinfoname:'',
          legendinfofilter:false,
        dialogTableVisible: false,
        dialogFormVisible: false,
        form: {
          region: '',
          date1:['医疗器械','新型医疗器械','新一代信息技术','节能环保','新能源','高端装备','机器人','新材料','碳材料','新能源汽车','智电汽车','高端纺织','集成电路'] ,

        },
          selectlayer:null,
          secondlayer:null,
          fullscreenLoading: false,
        formLabelWidth: '80px',
        legendlayer:'',
        cliplayers:null,
        retgeoinfo:[],
        drawgeom:null,
        drawstatus:false,
        onelandarrtibutes:null,
        pagebtn:null,
        vectorlayer:null,
        focusprojshow:false,
        closetree:true,
        newlayer:null,
        maps:null,
        layersarry:[],
        propertiesarry:[],
        type:"",
          basemaplayer:'',
          basezjlayer:'',
        mapInfoLayer:null,
        vectorSource:null,
        filterText: '',
        showattribute:false,
        showoneattribute:false,
        showdraw:false,
        showanaret:false,
        drawlayers:null,
        mapdraw:null,
        data: [{
          id: 1,
          label: '产业现状',
          serverurl:'',
          children: [{
            id: 4,
            label: '产业园区布局',
            serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
            layername:'xf:wj_cyyqbj2022',
            legendurl: require(''+'@/assets/img/legend/cyyq.jpg'+'')
          },
            {
              id: 9,
              label: '工业企业分布',
              serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
              layername:'xf:wjgyyd2022'
            },
            {
              id: 14,
              label: '2022年重大项目',
              serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
              layername:'xf:zdxm2022'
            },
            {
              id: 15,
              label: '现状用地分布',
              serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
              layername:'xf:wjxzydfb2022',
              legendurl: require(''+'@/assets/img/legend/xz.jpg'+'')
            },
            {
              id: 18,
              label: '9大重点产业',
              serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
              layername:'xf:wj95x92022',
              legendurl: require(''+'@/assets/img/legend/nineproduct.jpg'+'')
            },
            {
              id: 19,
              label: '5张产业名片',
              serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
              layername:'xf:wj95x52022',
              legendurl: require(''+'@/assets/img/legend/fiveidcard.jpg'+'')
            },
            {
              id: 20,
              label: '可储备工业用地',
              serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
              layername:'xf:wjkcbgyyd2022'
            },
            {
              id: 21,
              label: '武进专精特新企业',
              serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
              layername:'xf:wjzjtx2022'
            },
              {
                  id: 22,
                  label: '武进低效用地',
                  serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
                  layername:'xf:wjdxyd2022'
              },
              {
                  id: 23,
                  label: '武进连片开发',
                  serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
                  layername:'xf:wjlpkf2022'
              }
          ]
        }, {
          id: 2,
          label: '产业规划',
          children: [{
                  id: 5,
                  label: '常州市总体规划',
                  serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
                  layername:'xf:czsztgh2011_2020',
                  legendurl: require(''+'@/assets/img/legend/zg.jpg'+'')
              },{
            id: 6,
            label: '控制性详细规划',
            serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
            layername:'xf:wj_konggui2022',
            legendurl: require(''+'@/assets/img/legend/kg.jpg'+'')
          }
          ,
            {
              id: 10,
              label: '村镇建设控制区',
              serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
              layername:'xf:wj_czjskzq2022'
            },{
              id: 11,
              label: '基期地类',
              serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
              layername:'xf:wj_jqdl2022',
              legendurl: require(''+'@/assets/img/legend/gtjqdl.jpg'+'')
            }
            ,{
              id: 12,
              label: '建设用地管制区',
              serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
              layername:'xf:wj_jsydgzq2022',
              legendurl: require(''+'@/assets/img/legend/gtjsgzq.jpg'+'')
            }
            ,{
              id: 13,
              label: '土地用途区',
              serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
              layername:'xf:wj_tdytq2022',
              legendurl: require(''+'@/assets/img/legend/gttdytq.jpg'+'')
            }
            ,{
                  id: 16,
                  label: '基本农田保护区',
                  serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
                  layername:'xf:wj_jbntbhq2022'
              }

            ,{
              id: 17,
              label: '武进村庄规划',
              serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
              layername:'xf:wjczgh2018_2020',
              legendurl: require(''+'@/assets/img/legend/cg.jpg'+'')
            }
          ]
        }, {
          id: 3,
          label: '产业配套',
          children: [{
            id: 7,
            label: '武进医疗设施',
            serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
            layername:'xf:wjylss2018_m'
          }]
        },
            {
                id: 24,
                label: '辅助图层',
                children: [{
                    id: 25,
                    label: '武进区镇界',
                    serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
                    layername:'xf:wjzjm'
                }]
            }

        ],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
      }
    },
    created(){

    },
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val);
      },
      changepage(newV,oldV){
        console.log(newV)
        this.closetree=newV.sta
        var geojsonObject={}
        if(newV.btnum==1){
          this.pagebtn=1
           geojsonObject={"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[119.938243504,31.640018024],[119.938137872,31.639978024],[119.938135508,31.639982586],[119.938135085,31.639983415],[119.938135062,31.639983447],[119.9375174,31.639768312],[119.937469343,31.639762687],[119.937418664,31.639766535],[119.937376195,31.639777991],[119.937332031,31.639799671],[119.937331997,31.639799692],[119.937302857,31.639821767],[119.937274836,31.639858436],[119.937253378,31.63989263],[119.937253146,31.639893468],[119.937253123,31.639893511],[119.937144927,31.640283884],[119.937144982,31.640283888],[119.937219546,31.640297099],[119.937219275,31.640297977],[119.937137404,31.640551168],[119.937114864,31.640620876],[119.937067666,31.640766868],[119.937027803,31.64089017],[119.936896429,31.641304633],[119.936896417,31.641304685],[119.937588702,31.64154162],[119.938708178,31.641924752],[119.938708771,31.641923478],[119.938709159,31.641922644],[119.938941086,31.641426639],[119.938941476,31.641425806],[119.938196555,31.641172496],[119.938196509,31.64117248],[119.938196406,31.641172445],[119.938196424,31.641172409],[119.938315011,31.640930575],[119.938683793,31.640178508],[119.938684198,31.64017768],[119.938683982,31.640177605],[119.938566375,31.640136642],[119.938403202,31.640079807],[119.938403078,31.640079764],[119.938407352,31.64007042],[119.938407735,31.640069583],[119.938369802,31.640056921],[119.938356835,31.640052928],[119.938243504,31.640018024]]]},"properties":{"tdzl":"武进国家高新技术产业开发区龙域西路29号","yddw":"常州龙翔气弹簧股份有限公司","kid":"777777"}}]}
         this.addVectorlayer(geojsonObject)
          this.maps.getView().fit(geojsonObject.features[0])
        }
        if(newV.btnum==2){
          this.pagebtn=2
           geojsonObject ={"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[119.725162135,31.676535635],[119.725651966,31.676274615],[119.725474674,31.675989731],[119.724851792,31.676321652],[119.724784867,31.6762298],[119.724713262,31.676267955],[119.724277979,31.67567055],[119.723728106,31.675962966],[119.724230624,31.676652654],[119.722768842,31.677431571],[119.723111276,31.677901553],[119.725287799,31.676741768],[119.725162135,31.676535635]]]},"properties":{"LAYER":"2022省级","NAME":"武进国家农村产业融合发展示范园,（花木交易中心）","kid":"666666"}}]}
           this.addVectorlayer(geojsonObject)
           this.maps.getView().fit(geojsonObject.features[0])
        }
        if(newV.btnum==0){
          this.showdraw=true
          this.pagebtn=0
        }
        if(newV.sta==false&&newV.btnum==2){
          this.focusprojshow=true
        }else{
          this.focusprojshow=false
        }


      }
    },
    mounted() {
      let that=this
      that.initMap()
    },
    methods:{
        measureclick(data){
            if(data.status){
               this.drawstatus=true
            }else {
                this.drawstatus=false
            }
        },
        getlayerstyles(layernamech){
            var that=this
            getLayerStyle({layername:layernamech}).then(res=>{
                that.legendinfo=res.data
            })
        },
        setlegendstyle(rgb){
            return { "background-color": rgb};
        },
        selectstyleshow(val){


            var sqlfilter="1=1"

            //控制性详细规划
            if(this.legendlayer=='xf:wj_konggui2022'){
                sqlfilter= "YDDM like '%"+val+"%'"

            }
            //建设用地管制区
            if(this.legendlayer=='xf:wj_jsydgzq2022'){
                sqlfilter= "GZQLXDM like '%"+val+"%'"

            }
            //2022重大项目
            if(this.legendlayer=='xf:zdxm2022'){
                sqlfilter= "LB like '%"+val+"%'"

            }
            //常州市总体规划
            if(this.legendlayer=='xf:czsztgh2011_2020'){
                sqlfilter= "MARK like '%"+val+"%'"

            }
            //基期地类
            if(this.legendlayer=='xf:wj_jqdl2022'){
                sqlfilter= "DLMC like '%"+val+"%'"

            }
            //土地用途区
            if(this.legendlayer=='xf:wj_tdytq2022'){
                sqlfilter= "TDYTQLXDM like '%"+val+"%'"

            }
            //武进村庄规划
            if(this.legendlayer=='xf:wjczgh2018_2020'){
                sqlfilter= "YDXZ like '%"+val+"%'"

            }
            //武进连片开发
            if(this.legendlayer=='xf:wjlpkf2022'){
                sqlfilter= "SSBK like '%"+val+"%'"

            }
            //现状用地分布
            if(this.legendlayer=='xf:wjxzydfb2022'){
                sqlfilter= "YJDL like '%"+val+"%'"

            }
            //5张产业名片
            if(this.legendlayer=='xf:wj95x52022'){
                sqlfilter= "cylb like '%"+val+"%'"

            }
            //9大重点产业
            if(this.legendlayer=='xf:wj95x92022'){
                sqlfilter= "cylb like '%"+val+"%'"

            }

            if(this.legendinfoname==val &&  this.legendinfofilter){
                sqlfilter="1=1"
                this.legendinfofilter=!this.legendinfofilter

            }else{
                this.legendinfofilter=!this.legendinfofilter
                this.legendinfoname=val
            }
            var sellayername=this.legendlayer
            let params={
                LAYERS: sellayername,
                CQL_FILTER: sqlfilter
            }
            // console.log(this.newlayer)
            // console.log(params)
            this.newlayer.getSource().updateParams(params)
        },
        openselectdialog(){
            this.dialogFormVisible=true
          if(this.selectlayer==null){
              this.secondlayer=this.getlayersource('http://218.93.116.192:8087/geoserver/xf/wms','xf:wjkcbgyyd2022')
              this.selectlayer= this.getlayersource('http://218.93.116.192:8087/geoserver/xf/wms','xf:wj95x_circle')
              this.selectlayer.setVisible(false)
              this.secondlayer.setVisible(false)
              this.maps.addLayer(this.selectlayer)
              this.maps.addLayer(this.secondlayer)
          }
        },
      selchange(event){
        var selectlayer=this.selectlayer
          var sqlfilter="CYLB like '%"+event+"%'"
          var sellayername='xf:wj95x_circle'
          this.selectShowlayer(sellayername,sqlfilter)
      },
        closeselectdialog(){

            this.maps.removeLayer(this.secondlayer)
            this.maps.removeLayer(this.selectlayer)
            this.selectlayer=null
            this.dialogFormVisible=false
        },
      selectShowlayer(layername,filtsql){
          var sourcelayer=this.selectlayer
          var secondsourcelayer=this.secondlayer
          if(!sourcelayer.getVisible()){
              sourcelayer.setVisible(true)
              secondsourcelayer.setVisible(true)
          }

          let params={
            LAYERS: layername,
            CQL_FILTER: filtsql
          }
          sourcelayer.getSource().updateParams(params)
      },
      drawinfo(){
        var that=this
        this.drawstatus=true
        if(this.drawlayers!=null){
            this.mapdraw.setActive(true)
          return
        }
        const source = new VectorSource({wrapX: false});
        const vector = new VectorLayer({
          source: source,
          zIndex:9999
        });
        this.drawlayers=vector
        this.maps.addLayer(vector)
         var draw; // global so we can remove it later
          const value = 'Polygon';
          if (value !== 'None') {
             draw = new Draw({
              source: source,
              type: value,
            });

            this.mapdraw=draw
            this.maps.addInteraction(draw);
            draw.on('drawend',function (e) {
              that.drawgeom=e.feature.getGeometry()
                draw.setActive(false)

              // vector.getSource().on('addfeature', function () {
              //   that.dtlayer.setExtent(vector.getSource().getExtent());
              // });
            })
          }
      },
      delgeoinfo(sta){

        this.maps.removeInteraction(this.mapdraw)
        this.maps.removeLayer(this.drawlayers)
        this.maps.removeLayer(this.cliplayers)
          this.maps.removeLayer(this.selectlayer)
          this.maps.removeLayer(this.secondlayer)
          this.selectlayer=null
          this.dialogFormVisible=false
        this.drawlayers=null
        this.drawstatus=false
        this.showanaret=false
          if(sta=='close'){
              this.showdraw=false
          }
          // this.showdraw=false
      },
        openFullScreen(val) {
            const loading = this.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            setTimeout(() => {
                loading.close();
            }, 2000);

    },
      commitgeoinfo(){
        var that=this
          const loading = this.$loading({
              lock: true,
              text: 'Loading',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
          });
        // const vectorSource = new VectorSource();
        // const vector = new VectorLayer({
        //   source: vectorSource,
        //   style: new Style({
        //     stroke: new Stroke({
        //       color: 'rgba(0, 0, 255, 1.0)',
        //       width: 2,
        //     }),
        //   }),
        // });
        // this.maps.addLayer(vector)
        const featureRequest = new WFS().writeGetFeature({
          srsName:'EPSG:4490',
          featureNS: 'cydt-wfs',
          featurePrefix: 'xf',
          featureTypes: ['xf:wj_jbntbhq2022','xf:wj_jsydgzq2022','xf:wj_konggui2022','xf:wj_czjskzq2022','xf:wjczgh2018_2020'],
          outputFormat: 'application/json',
          filter: intersectsFilter('geom',that.drawgeom,'EPSG:4490')
        });
        // then post the request and add the received features to a layer
        //本地跨域问题修改url打包服务器应注意
        fetch('http://218.93.116.192:8087/geoserver/wfs', {
          method: 'POST',
          body: new XMLSerializer().serializeToString(featureRequest),
        })
                .then(function (response) {

                  return response.json();
                })
                .then(function (json) {
                  // let feasarr =[];
                  that.retgeoinfo=[]
                  that.retgeoinfo= sortFeature(json)
                  if(! that.showanaret){
                    that.showanaret=true
                  }
                    setTimeout(() => {
                        loading.close();
                    }, 1000);
                  //重绘几何
                  // vectorSource.addFeatures(feasarr);
                  // that.maps.removeInteraction(draw);
                  // console.log(VectorLayer.getFeatures())
                });

      },
      addVectorlayer(geojsonObject){
        if(this.vectorlayer!=null){
          this.maps.removeLayer(this.vectorlayer)
        }
        const styles = {
          'MultiPolygon': new Style({
            stroke: new Stroke({
              color: 'red',
              width: 2,
              lineDash:[20]
            }),
            fill: new Fill({
              color: 'rgba(255, 255, 0, 0.5)',
            }),
            text: new Text({
              font: '20px Microsoft YaHei',
              text:  geojsonObject.features[0].properties.kid,
              fill: new Fill({
                color: '#000'
              })
            })
          }),
          'Polygon': new Style({
            stroke: new Stroke({
              color: 'red',
              lineDash: [4],
              width: 3,
            }),
            fill: new Fill({
              color: 'rgba(0, 0, 255, 0.1)',
            }),
          }),
            'Point': new Style({
                fill: new Fill({
                    color: 'rgba(255, 255, 255, 0.2)',
                }),
                stroke: new Stroke({
                    color: 'rgba(0, 0, 0, 0.5)',
                    lineDash: [10, 10],
                    width: 2,
                }),
                image: new CircleStyle({
                    radius: 20,
                    stroke: new Stroke({
                        color: 'rgba(255, 0, 0, 0.7)',
                    }),
                    fill: new Fill({
                        color: 'rgba(255, 0, 0, 0.2)',
                    }),
                }),

            })
        };
        const vectorSource = new VectorSource({
          features: new GeoJSON().readFeatures(geojsonObject),
        });
        const styleFunction = function (feature) {
          return styles[feature.getGeometry().getType()];
        };
        const vectorLayer = new VectorLayer({
          source: vectorSource,
          style: styleFunction,
        });
        this.maps.addLayer(vectorLayer)
        const feature = vectorSource.getFeatures()[0];
        const polygon = feature.getGeometry();
        this.maps.getView().fit(polygon,{maxZoom:15})
        this.vectorlayer=vectorLayer
      },
      getlayersource(url,layername){
        const layers = new TileLayer({
          extent: [119.66566467285156,31.334217071533203,120.20945739746094, 32.104400634765625],
          source: new TileWMS({
            url: url,
            params: {'LAYERS':layername, 'TILED': true},
            serverType: 'geoserver',
            transition: 0,
          }),
        })
        this.newlayer=layers
        return layers;
      },
      addchildrenlayertomap(val1){
        var that=this
        var isnewcheck=true
        that.layersarry.forEach(function (arr) {
          if(val1.id==arr.id){
            isnewcheck=false
          }
        })
        if(isnewcheck){
          const childrenlayer=that.getlayersource(val1.serverurl,val1.layername)
          that.layersarry.push({'id':val1.id,'layer':childrenlayer,'layername':val1.label})
            console.log(val1.label)
            that.legendlayer=val1.layername
            that.getlayerstyles(val1.label)
          that.maps.addLayer(childrenlayer)
        }
      },
      addlayertomap(val1,val2){
        var that=this
        var cancelcheck=true
        val2.checkedNodes.forEach(function (arr) {
          if(val1.id==arr.id){
            const layer=that.getlayersource(val1.serverurl,val1.layername)
            that.layersarry.push({'id':val1.id,'layer':layer,'layername':val1.label})
              that.legendlayer=val1.layername
              that.getlayerstyles(val1.label)
            that.maps.addLayer(layer)
            cancelcheck=false
          }
        })
        if(cancelcheck){
          that.removelayerfrommap(val1)
        }
      },
      removelayerfrommap(val1){
        for(let i=0;i<this.layersarry.length;i++){
          if(this.layersarry[i].id==val1.id){
            this.maps.removeLayer(this.layersarry[i].layer)
            this.layersarry.splice(i,1)
            break;
          }
        }
      },
      childrenlayeraddorremove(val1,val2){
        var that=this
        if('children' in val1){
          var cancelcheck=true
          val2.checkedNodes.forEach(function (arr) {
            if(val1.id==arr.id){//选中，添加图层
              for(let j=0;j<val1.children.length;j++){
                that.addchildrenlayertomap(val1.children[j])
              }
              cancelcheck=false
            }
          })
          if(cancelcheck){//取消选中，移除图层
            for(let j=0;j<val1.children.length;j++){
              that.removelayerfrommap(val1.children[j])
            }
          }
        }else{
          that.addlayertomap(val1,val2)
        }
      },
      setlayer(val1,val2){
        var that=this

        if(val2.checkedNodes.length>0){//目录树上有选择
          that.childrenlayeraddorremove(val1,val2)
        }else{//目录树上没有选择，全部移除
          if('children' in val1){
            for(let j=0;j<val1.children.length;j++){
              that.removelayerfrommap(val1.children[j])
            }
          }else{
            that.removelayerfrommap(val1)
          }
        }

      },
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      getlayerinfo(layer,evt){
        var that=this
        var view=that.maps.getView()
        var viewResolution = view.getResolution();
        var propertiesformany={}
        var source =  layer.layer.get('visible') ? layer.layer.getSource():that.newlayer.getSource();
        var url = source.getFeatureInfoUrl(
                evt.coordinate, viewResolution, view.getProjection(),
                {'INFO_FORMAT': 'application/json', 'FEATURE_COUNT': 50})
        if (url) {
          console.log(url)
          //本地跨域问题修改url打包服务器应注意
          axios.get(url)
                  .then(response => {
                    if(response.data.features.length>0){
                      // const multiPolygon=new MultiPolygon(response.data.features[0].geometry.coordinates)
                      // view.fit(multiPolygon)
                       // console.log(response.data)
                      for(var i=0;i<response.data.features.length;i++){
                        propertiesformany=Object.assign(propertiesformany,response.data.features[i].properties)
                      }
                      that.showattribute=true
                        // console.log(response.data)
                      // propertiesformany=response.data.features[0].properties
                      that.addVectorlayer(response.data)
                    }else{

                      that.showattribute=false
                    if(that.showoneattribute||that.focusprojshow){}else{
                      that.maps.removeLayer(that.vectorlayer)
                    }

                    }
                    // view.fit([evt.coordinate[0]-0.05, evt.coordinate[1]-0.05,evt.coordinate[0]+0.05, evt.coordinate[1]+0.05]);
                  })
                  .catch(error => {
                    console.log(error)
                  })
                  .finally(()=>{
                    that.propertiesarry.push({'layername':layer.layername,'properties':propertiesformany})
                  }

                  )

        }
      },
      initMap() {
        var that=this
        console.log("开始加载地图！")
        var projection = new Projection({
          code: 'EPSG:4490',
          units: 'degrees',
          axisOrientation: 'neu',
          global: true
        });
        projection.setExtent([-180,-90,180,90]);
        projection.setWorldExtent([-180,-90,180,90]);
        // var projection= getProjection('EPSG:4326');
        //   var format = 'image/png';
        const mousePositionControl = new MousePosition({
          coordinateFormat: createStringXY(4),
          projection: 'EPSG:4326',
          className: 'custom-mouse-position',
          undefinedHTML: '&nbsp',
        });
        // var untiled = new ImageLayer({
        //   source: new ImageWMS({
        //     ratio: 1,
        //     url: 'http://218.93.116.192:8087/geoserver/xf/wms',
        //     params: {'FORMAT': format,
        //       'VERSION': '1.1.1',
        //       "STYLES": '',
        //       "LAYERS": 'xf:gyyd_m0810',
        //       "exceptions": 'application/vnd.ogc.se_inimage',
        //     }
        //   })
        // });
        var webKey = "137c55da7638cc1eb357a0d41d99719d";
        var wmtsUrl_1 = 'http://t{0-7}.tianditu.gov.cn/vec_c/wmts?tk='; //矢量底图
        var wmtsUrl_2 = 'http://t{0-7}.tianditu.gov.cn/cva_c/wmts?tk='; //矢量注记
        var wmtsUrl_3 = 'http://t{0-7}.tianditu.gov.cn/img_w/wmts?tk='; //影像底图
        var wmtsUrl_4 = 'http://t{0-7}.tianditu.gov.cn/cia_w/wmts?tk='; //影像注记
        var wmtsUrl_5 = 'http://t{0-7}.tianditu.gov.cn/ter_w/wmts?tk='; //地形底图
        var wmtsUrl_6 = 'http://t{0-7}.tianditu.gov.cn/cta_w/wmts?tk='; //地形注记
        var wmtsUrl_7 = 'http://t{0-7}.tianditu.gov.cn/ibo_w/wmts?tk='; //境界（省级以上）
        var wmtsUrl_8 = 'http://t{0-7}.tianditu.gov.cn/eva_w/wmts?tk='; //矢量英文注记
        var wmtsUrl_9 = 'http://t{0-7}.tianditu.gov.cn/eia_w/wmts?tk='; //影像英文注记
        var wmtsUrl_10 = 'http://192.168.13.17:8089/geoserver/gwc/service/wmts'; //影像英文注记
          var dtlayer=that.getDtWMTSLayer(wmtsUrl_1+webKey,'vec_c')
          that.basemaplayer=dtlayer
          var zjlayer=that.getDtWMTSLayer(wmtsUrl_2+webKey,'cva_c')
          that.basezjlayer=zjlayer


        var map = new Map({
          controls: defaultControls(
                  {
                    zoom: false,
                    rotate: false,
                    attribution: false
                  }
          ).extend([new FullScreen(),
            // new ScaleLine({
            //   units: "metric"})
          ]),
          layers: [
              dtlayer,zjlayer
          ],
          target: 'oneMap',
          view: new View({
            projection:projection,
            center: [0,0],
            zoom: 8
          })
        });
        that.maps=map
        map.getView().fit([119.6636833624323, 31.33182968686947,120.12129162382348, 31.77128060702411], map.getSize());
        this.$store.state.map=map
        map.on('singleclick', function(evt){
          if(that.drawstatus){return}
          // console.log(map.getLayerGroup())
          var view = map.getView();
          var viewResolution = view.getResolution();
          const feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {
            return feature;
          });
          if(feature){
            if(that.pagebtn==1){

              that.showoneattribute=true
            }
            if(that.pagebtn==2){
              that.focusprojshow=true
            }
          }else{
            that.showoneattribute=false
            that.focusprojshow=false
            that.showattribute=false
            that.maps.removeLayer(that.vectorlayer)
          }
          if(that.layersarry.length>0){
           that.layersarry.forEach(function (layer, i) {
             that.propertiesarry=[]
             that.getlayerinfo(layer,evt)
            });
          }else{
            that.showattribute=false
           // that.maps.removeLayer(that.vectorlayer)
          }
            if(that.selectlayer!=null){
                that.propertiesarry=[]
                var layerbuild1={layer:that.selectlayer,layername:'推荐选址区域'}
                // var layerbuild2={layer:that.secondlayer,layername:'推荐选址区域'}
                that.getlayerinfo(layerbuild1,evt)
                // that.getlayerinfo(layerbuild2,evt)
            }
        })

      },
        //获取底图XYZ
        getDtXYZLayer(url){
            var sourceSatellite = new XYZ({
                url: url
            });
            var tileSatellite = new TileLayer({

                source: sourceSatellite

            });
           return tileSatellite
        },
        //获取底图WMTS
        getDtWMTSLayer(url,layermatrix){
            var projection = new Projection({
                code: 'EPSG:4490',
                units: 'degrees',
                axisOrientation: 'neu',
                global: true
            });
            projection.setExtent([-180,-90,180,90]);
            projection.setWorldExtent([-180,-90,180,90]);
            const projectionExtent = projection.getExtent();
            const size = getWidth(projectionExtent) / 256;
            const resolutions = new Array(19);
            const matrixIds = new Array(19);
            for (let z = 0; z < 19; ++z) {
                // generate resolutions and matrixIds arrays for this WMTS
                resolutions[z] = size / Math.pow(2, z);
                matrixIds[z] = z;
            }
            var forlayername=  layermatrix.substring(0,layermatrix.indexOf("_"))
            var matrixset=layermatrix.substring(layermatrix.indexOf("_") + 1)
                var dtlayer=new TileLayer({
                    opacity: 1,
                    source: new WMTS({
                        url: url,
                        layer: forlayername,
                        matrixSet: matrixset,
                        format: 'tiles',
                        style: 'default',
                        projection: projection,
                        tileGrid: new WMTSTileGrid({
                            origin: getTopLeft(projectionExtent),
                            resolutions: resolutions,
                            matrixIds: matrixIds
                        }),
                        wrapX: true,
                    })
                })

        return dtlayer;

        },
        addbaseimglayer(val){
            var basemaplayer1=null
            var basezjlayer1=null
            var layersArray = this.maps.getLayers();
            var webKey = "137c55da7638cc1eb357a0d41d99719d";
            var wmtsUrl_1 = 'http://t{0-7}.tianditu.gov.cn/vec_c/wmts?tk='; //矢量底图
            var wmtsUrl_2 = 'http://t{0-7}.tianditu.gov.cn/cva_c/wmts?tk='; //矢量注记
            if(val==='电子影像'){
                this.maps.removeLayer(this.basezjlayer)
                this.maps.removeLayer(this.basemaplayer)
                 basemaplayer1= this.getDtXYZLayer('http://t3.tianditu.com/DataServer?tk=137c55da7638cc1eb357a0d41d99719d&T=img_w&x={x}&y={y}&l={z}')
                 basezjlayer1=this.getDtXYZLayer('http://t3.tianditu.com/DataServer?tk=137c55da7638cc1eb357a0d41d99719d&T=cia_w&x={x}&y={y}&l={z}')
                this.basezjlayer=basezjlayer1
                this.basemaplayer=basemaplayer1
                layersArray.insertAt(0,basemaplayer1);
                layersArray.insertAt(1,basezjlayer1);
                // this.maps.addLayer(basemaplayer)
                //  this.maps.addLayer(basezjlayer)
            }
            if(val==='电子地图'){
                this.maps.removeLayer(this.basezjlayer)
                this.maps.removeLayer(this.basemaplayer)
                 basemaplayer1= this.getDtWMTSLayer(wmtsUrl_1+webKey,'vec_c')
                 basezjlayer1=this.getDtWMTSLayer(wmtsUrl_2+webKey,'cva_c')
                this.basezjlayer=basezjlayer1
                this.basemaplayer=basemaplayer1
                layersArray.insertAt(0,basemaplayer1);
                layersArray.insertAt(1,basezjlayer1);
                // this.maps.addLayer(basemaplayer)
                // this.maps.addLayer(basezjlayer)
            }


        },
      closesonwind(data){

        if(data.status){
          this.cliplayeradd(data)
        }else {
          this.showanaret=data.status
        }
      },
        selectMapOrImg(val){
         this.addbaseimglayer(val)
        },
      cliplayeradd(e){
        var that=this
        if(that.cliplayers!=null){
          that.maps.removeLayer(that.cliplayers)
        }
        const cliplayer=this.getlayersource(e.serverurl,e.layername)
        const style = new Style({
          fill: new Fill({
            // color:'transparent',
            strokeStyle:'red',
          }),
        });
        cliplayer.on('prerender', function (e) {
           cliplayer.setExtent(that.drawgeom.getExtent());
          const vectorContext = getVectorContext(e);
          // e.context.globalCompositeOperation = 'destination-in';
          let ctx = e.context;
          ctx.save();
          that.drawlayers.getSource().forEachFeature(function (feature) {
            vectorContext.drawFeature(feature, style);
          });
          e.context.globalCompositeOperation = 'source-over';
          ctx.clip();
        });
        cliplayer.on('postrender', function (e) {
          let ctx = e.context;
          ctx.restore();
        })
        this.maps.addLayer(cliplayer)
        that.cliplayers=cliplayer
      },


    }
  }
</script>

<style >
  @import 'myMap.scss';
</style>
